package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.ListNode;

/**
 * @Author fengye
 * @Date 2023/4/8 11:09
 **/
public class DeleteListDuplicates83 {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return null;
        }

        if(head.next == null) {
            return head;
        }

        while (head.next != null && head.val == head.next.val) {
            ListNode temp = head;
            head = head.next;
            temp.next = null;
        }

        ListNode prev = head;
        ListNode pos = head;
        ListNode next = head.next;
        while (next != null) {
            if(pos.val != next.val) {
                prev = pos;
                pos = next;
                next = next.next;
            } else {
                if (prev == head) {
                    pos = next;
                    next = next.next;
                    prev.next = null;
                    head.next = prev = pos;
                } else {
                    ListNode temp = next;
                    next = next.next;
                    pos.next = next;
                    temp.next = null;
                }
            }
        }
        return head;
    }
}
